﻿using System;
using System.ComponentModel;
using DevExpress.Xpf.Map;
using Loki.UI;
using Loki.Utils;
using Luna.Model.Connector;

namespace Luna.UI.Crm
{
    public class GeoSearchViewModel : Screen
    {
        public GeoSearchViewModel()
        {
            DisplayName = "Geolocalisation";
        }

        #region CenterPoint

        private static PropertyChangedEventArgs argsCenterPointChanged = ObservableHelper.CreateChangedArgs<GeoSearchViewModel>(x => x.CenterPoint);

        private static PropertyChangingEventArgs argsCenterPointChanging = ObservableHelper.CreateChangingArgs<GeoSearchViewModel>(x => x.CenterPoint);

        private GeoPoint centerPoint;

        public GeoPoint CenterPoint
        {
            get
            {
                return centerPoint;
            }

            set
            {
                if (value != centerPoint)
                {
                    NotifyChanging(argsCenterPointChanging);
                    centerPoint = value;
                    NotifyChanged(argsCenterPointChanged);
                }
            }
        }

        #endregion CenterPoint

        #region Address

        private static PropertyChangedEventArgs argsAddressChanged = ObservableHelper.CreateChangedArgs<GeoSearchViewModel>(x => x.Address);

        private static PropertyChangingEventArgs argsAddressChanging = ObservableHelper.CreateChangingArgs<GeoSearchViewModel>(x => x.Address);

        private string address;

        public new string Address
        {
            get
            {
                return address;
            }

            set
            {
                if (value != address)
                {
                    NotifyChanging(argsAddressChanging);
                    address = value;
                    NotifyChanged(argsAddressChanged);
                }
            }
        }

        #endregion Address

        protected override void OnInitialize()
        {
            base.OnInitialize();
            this.WatchPropertyChanged(this, c => c.Address, c => c.Address_Changed);
            CenterPoint = new GeoPoint(48.8680202, 2.3790747);
        }

        private void Address_Changed(object sender, EventArgs e)
        {
            DoSearch();
        }

        public IGeolocalizer Localizer { get; set; }

        private void DoSearch()
        {
            var result = Localizer.Localize(Address);
            if (result != null)
            {
                CenterPoint = new GeoPoint(result.Latitude, result.Longitude);
            }
        }
    }
}